import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Drawer,
  Row,
  Col,
  Switch,
  Checkbox, Tooltip, Select, Icon as AIcon
} from 'antd';

import water_img from './../../images/xfs-blue.png';
import press_img from './../../images/xfs-blue.png';
import press_red from './../../images/xfs-red.png';
import flow_blue from './../../images/xfs-blue.png';
import flow_red from './../../images/xfs-red.png';
import styles from './../Home/index.less';
import Detail from './../Pressure_sensors/Detail'
import PressDetail from './../Pressure_sensors/Detail'
// import FlowmeterDetail from './../FlowMeter_sensors/Detail'
import './../Home/openlayers.less';
import Map from 'ol/Map';
import filter from 'lodash/filter'
import View from 'ol/View';
import Overlay from 'ol/Overlay';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import {getTransform} from 'ol/proj';
import Polygon from 'ol/geom/Polygon';
import {boundingExtent, getCenter} from 'ol/extent';
import {Vector} from 'ol/layer';
import {Vector as VectorSource} from 'ol/source';
import Feature from 'ol/Feature';
import {Icon, Stroke, Text, Style, Fill} from 'ol/style';
import Point from 'ol/geom/Point';
import {fromLonLat, toLonLat} from 'ol/proj';
import find from 'lodash/find';

const FormItem = Form.Item;
const {confirm} = Modal;
const Option = Select.Option;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({meters_map, loading, global}) => ({
  meters_map,
  global,
  loading: loading.models.meters_map,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      editRecord2:{},
      selectedRowKeys: [],
      all_vendors: [],
    };
  }


  componentDidMount() {
    const that = this;
    const {dispatch} = this.props;
    const {
      meters_map: {pageLoaded, scrollData},
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    if (pageLoaded) {
      dispatch({
        type: 'meters_map/fetch',
        callback: () => {
          const {dispatch} = this.props;
          dispatch({
            type: 'meters_map/changeTableY',
            callback: function () {
              that.renderMap();
            },
          });
        },
      });
    } else {
      const {
        meters_map: {searchParams},
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'meters_map/fetch',
        payload: searchParams,
        callback: () => {
          const {dispatch} = this.props;
          dispatch({
            type: 'meters_map/changeLoaded',
          });
          dispatch({
            type: 'meters_map/changeTableY',
            callback: function () {
              that.renderMap();
            },
          });
        },
      });

    }

    this.timer = setInterval(function () {
      dispatch({
        type: 'meters_map/fetch',
        // payload: {},
        callback: () => {
          that.renderPoint(true);
        },
      });
    }, 10000);

  }

  componentWillUnmount() {
    if (this.timer) {
      console.log('clearInterval(this.timer)');
      clearInterval(this.timer);
    }
    if (this.onePointDataTimer) {
      clearTimeout(this.onePointDataTimer);
    }

  }
  renderMap = () => {
    const that = this;
    const {dispatch, meters_map: {data, layers, center, zoom}} = this.props;
    let map = this.map = new Map({
      target: 'mapDiv',
      layers: layers,
      view: new View({
        center: fromLonLat(gcoord.transform(
          center,    // 经纬度坐标
          gcoord.GCJ02,               // 当前坐标系
          gcoord.WGS84                 // 目标坐标系
        )),//经纬度
        zoom: zoom,
        maxZoom: 21,
        projection: 'EPSG:3857'
      }),
    });



    console.log('renderMap');
    this.renderPoint()
    map.on('moveend', function (e) {
      let zoom = map.getView().getZoom();  //获取当前地图的缩放级别
      let center = map.getView().getCenter();
      // console.log(toLonLat(center));
      dispatch({
        type: 'meters_map/changeOneState',
        payload: {
          zoom, center: toLonLat(center),
        },
      });
    });

    //绘制弹出框
    let press_container = document.getElementById('press-popup');
    let header = document.getElementById('popup-header');
    let popupCloser = document.getElementById('popup-closer');
    let press_popup = new Overlay({
      //设置弹出框的容器
      element: press_container,
      //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
      autoPan: true,
    });
    popupCloser.addEventListener('click', function () {
      press_popup.setPosition(undefined);
    });

    map.on(['click'], function (e) {
      console.log(toLonLat(e.coordinate));
      var feature = map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
        return feature;
      });
      if (feature) {
        console.log('feature', feature.get('data_set'));
        if(!feature.get('data_set')){
          return
        }
        let ground = feature.get('data_set').ground_set;

        let coordinates = feature.getGeometry().getCoordinates();
        let iconName = feature.get('number');
        let data_set = feature.get('data_set');
        if (data_set.ground_set === 'press') {
          that.setState({
            editRecord: data_set,
          });
          that.fetOnePointData(data_set.id, coordinates, header, iconName, press_popup);
          // pipe_popup.setPosition(undefined);
          // water_popup.setPosition(undefined);
          // workstations1_popup.setPosition(undefined);
          // appendageCharac_popup.setPosition(undefined);
        }
      }else{
        if (e.type === 'click') {
          press_popup.setPosition(undefined);
        }
        if (that.onePointDataTimer) {
          clearTimeout(that.onePointDataTimer);
        }
      }
    })
  };
  fetOnePointData = (id, coordinates, header, iconName, press_popup) => {
    console.log('fetOnePointData')
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'meters_map/fetchPointData',
      payload: {
        id: id,
      },
      callback: () => {
        if (coordinates) {
          header.innerHTML = '<span>消防栓 : ' + iconName + '</span>';
          press_popup.setPosition(coordinates);
          this.map.addOverlay(press_popup);
        }
        if (that.onePointDataTimer) {
          clearTimeout(that.onePointDataTimer);
        }
        that.onePointDataTimer = setTimeout(function() {
          that.fetOnePointData(id);
        }, 10000);


      },
    });
  };
  renderPoint = (is_load) => {
    const {
      dispatch,
      meters_map: { pressData, pressVisiable, }
    } = this.props;
    //绘制点
    if (this.pressLayer) {
      this.map.removeLayer(this.pressLayer);
    }
    if (pressVisiable) {
      console.log('pressData', pressData)
      let pressFeature = [];
      for (let i = 0; i < pressData.length; i++) {
        if (pressData[i].longitude) {
          let img = press_img;
          let err = false
          if (pressData[i].online_status === -1) {
            img = press_red;
            err = true
          }
          if (pressData[i].alarm===1) {
            img = press_red
            err = true
          }
          let point = this.setPoint([pressData[i].longitude, pressData[i].latitude], {
            ...pressData[i],
            ground_set: 'press',
          }, img, err);
          pressFeature.push(point);
        }
      }
      this.pressSource = new VectorSource({
        features: pressFeature,
      });
      this.pressLayer = new Vector({
        source: this.pressSource,
        zIndex: 15,
      });
      // 将标注图层添加到地图上
      this.map.addLayer(this.pressLayer);
    }
    if(!is_load){
      let view = this.map.getView();
      // view.setZoom(14);
      let Coordinates = [];
      for (let i = 0; i < pressData.length; i++) {
        Coordinates.push(fromLonLat([pressData[i].longitude, pressData[i].latitude]));
      }
      let extent = boundingExtent(Coordinates);
      let center = getCenter(extent);   //获取边界区域的中心位置
      view.setCenter(center);  //设置当前地图的显示中心位置
      view.fit(extent, {padding: [150, 200, 50, 100]});
    }


  };
  setPoint = (coord, data_set, img, err) => {
    let point = new Feature({
      geometry: new Point(fromLonLat(gcoord.transform(
        coord,    // 经纬度坐标
        gcoord.GCJ02,               // 当前坐标系
        gcoord.WGS84                 // 目标坐标系
      ))),
      name: data_set.name,
      number: data_set.number,
      data_set: data_set,
    });
    //设置图标的样式
    point.setStyle(this.setMakerStyle(point, img, err));
    return point;
  };
  setMakerStyle = (feature, img, err) => {
    const {dispatch, meters_map: {show_type}} = this.props;
    let zoom = this.map.getView().getZoom();  //获取当前地图的缩放级别
    return new Style({
      /**{olx.style.IconOptions}类型*/
      image: new Icon({
        anchorOrigin: 'top-right',
        offsetOrigin: 'top-right',
        //图标缩放比例
        scale: 1,
        //透明度
        opacity: 1,
        //图标的url
        src: img,
      }),
      text: new Text({
        //位置
        textAlign: 'center',
        //基准线
        textBaseline: 'middle',
        //文字样式
        font: 'normal 14px 微软雅黑',
        offsetY: 26,
        //文本内容
        text: `${!show_type ? '' : show_type == '1' ? feature.get('data_set').name : feature.get('data_set').number}`,
        //文本填充样式（即文字颜色）
        fill: new Fill({color: '#ffffff'}),
        backgroundFill: err ? new Fill({color: '#ec0000'}) : new Fill({color: '#3b79fe'}),
        padding: [2, 1, 0, 3],
      }),
    });
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'meters_map/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        that.renderPoint()
      },
    });
  };

  renderSimpleForm() {
    const that = this
    const {
      form: {getFieldDecorator},
      meters_map: {searchParams, show_type},
    } = this.props;
    return (
      <Form layout="inline" className="search-form map-search2">

        <FormItem style={{color: '#fff', fontWeight: "bold"}} label="消防栓编号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{width: '100px'}} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem style={{color: '#fff', fontWeight: "bold"}} label="资产编号">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{width: '100px'}} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem style={{color: '#fff', fontWeight: "bold"}} label="在线状态">
          {getFieldDecorator('online_status', {
            initialValue: searchParams.online_status,
          })(
            <Select style={{width: '100px'}} allowClear>
              <Option value="">全部</Option>
              <Option value="1">在线</Option>
              <Option value="-1">离线</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem style={{color: '#fff', fontWeight: "bold"}} label="报警状态">
          {getFieldDecorator('alarm', {
            initialValue: searchParams.alarm,
          })(
            <Select style={{width: '100px'}} allowClear>
              <Option value={''}>全部</Option>
              <Option value={'-1'}>正常</Option>
              <Option value={'1'}>报警</Option>
            </Select>,
          )}
        </FormItem>
        {/*    <FormItem label="口径">
          {getFieldDecorator('caliber', {
            initialValue: searchParams.caliber,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const {form} = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>
        <FormItem style={{color: '#fff', fontWeight: "bold"}} label="">
          {getFieldDecorator('show_type', {
            initialValue: show_type,
          })(
            <Radio.Group onChange={(e) => {
              console.log(e.target.value)
              this.props.dispatch({
                type: 'meters_map/changeOneState',
                payload: {
                  show_type: e.target.value
                },
                callback: function () {
                  that.renderPoint()
                }
              });
            }}>
              <Radio.Button value="">不显示</Radio.Button>

              <Radio.Button value="2">显示编号</Radio.Button>
              <Radio.Button value="1">显示资产编号</Radio.Button>
            </Radio.Group>
          )}
        </FormItem>
      </Form>
    );
  }

  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        meters_map: {searchParams},
      } = this.props;
      const {form} = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      name:'',
      number:'',
      imei:'',
      address:'',
      online_status:'',
      alarm:'',
    });
  };


  render() {
    const that = this;
    const {
      dispatch,
      meters_map: {pointData, waterVisiable, OriginData},
      global: {gridTableW,compare_data},
    } = this.props;
    let normal=filter(OriginData,function (item,index){
      return item.online_status===1&&item.alarm===-1
    })
    let NotOnline=filter(OriginData,function (item,index){
      return item.online_status===-1
    })
    let alarm=filter(OriginData,function (item,index){
      return item.alarm===1
    })
    return <div style={{
      height: '100%',
      width: '100%',
      overflow: 'hidden',
      position: 'relative',
    }}>

      <div id={'mapDiv'} style={{
        display: 'flex',
        height: '100%',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        background: '#000',
      }}>
      </div>
      <div style={{    position: "absolute",
        display:'flex',
        right: '20px',
        top: '20px',
        bottom: '20px',
        filter:'opacity(0.85)',
        background: '#001529',
        width:'250px',
        padding:'20px 15px',
        // display:'flex',
        flexDirection: "column",
        overflowY: "auto"}}>
        <div className={styles.dashboard_top_item} style={{height:'auto'}}>
          <h3>消防栓总数</h3>
          <p >{OriginData.length} <span>个</span></p>
          <span className={styles.border_top}></span>
          <span className={styles.border_right}></span>
          <span className={styles.border_left}></span>
        </div>
        <div className={styles.dashboard_top_item} style={{height:'auto'}}>
          <h3>报警设备数量</h3>
          <p style={{color:'red'}}> {alarm.length} <span>个</span></p>
          <span className={styles.border_top}></span>
          <span className={styles.border_right}></span>
          <span className={styles.border_left}></span>
        </div>
        <div className={styles.dashboard_top_item}  style={{flex:1,marginBottom:'0',overflow:"auto"}}>
          <h3>报警设备</h3>
          <div style={{margin:'5px -5px'}}>
            {
              alarm.map((item,index)=>{
                let colors=['magenta','red','volcano','orange','gold']
                return <Fragment key={index}>
                  <Tag onClick={()=>{
                    this.setState({
                      editRecord2:item,
                      infoModal2:true
                    })
                  }}  style={{marginBottom:'5px',marginLeft:'5px',cursor:'pointer'}} color={colors[index%6]}>{item.name}</Tag>
                </Fragment>
              })
            }

          </div>
        </div>

      </div>
      <div id="press-popup" className="ol-popup">
        <a href="#" id="popup-closer" className="ol-popup-closer"></a>
        <div id="popup-header" className={'ol-popup-header'}></div>
        <div id="popup-content" className={'ol-popup-content'}>
          <table className={'custom-table'}>
            <tbody>
            <tr>
              <td className={'custom-table-title'}>资产编号</td>
              <td className={'custom-table-value'}>{pointData.name}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>在线状态</td>
              <td className={'custom-table-value'}>{pointData.online_status===1?'在线':'离线'}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>报警</td>
              <td className={'custom-table-value'}>{pointData.alarm===1?'报警':'正常'}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>地址</td>
              <td className={'custom-table-value'}>{pointData.address}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>经度</td>
              <td className={'custom-table-value'}>{pointData.longitude}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>纬度</td>
              <td className={'custom-table-value'}>{pointData.latitude}</td>
            </tr>

            <tr>
              <td className={'custom-table-title'}>压力</td>
              <td className={'custom-table-value'}>{(pointData.latest_data&&pointData.latest_data.rtu&&pointData.latest_data.rtu.parameters)?(pointData.latest_data.rtu.parameters.pressure+`(${ pointData.latest_data.rtu.parameters.pressure_unit})`):''}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>累计流量</td>
              <td className={'custom-table-value'}>{(pointData.latest_data&&pointData.latest_data.rtu&&pointData.latest_data.rtu.parameters)?(pointData.latest_data.rtu.parameters.cumulative_flow+`(${ pointData.latest_data.rtu.parameters.cumulative_flow_unit})`):''}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>瞬时流量</td>
              <td className={'custom-table-value'}>{(pointData.latest_data&&pointData.latest_data.rtu&&pointData.latest_data.rtu.parameters)?
                (pointData.latest_data.rtu.parameters.instantaneous_flow+`(${ pointData.latest_data.rtu.parameters.instantaneous_flow_unit})`):''}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>温度</td>
              <td className={'custom-table-value'}>{(pointData.latest_data&&pointData.latest_data.rtu&&pointData.latest_data.rtu.parameters)?
                (pointData.latest_data.rtu.parameters.temperature+`(${ pointData.latest_data.rtu.parameters.temperature_unit})`):''}</td>
            </tr>
            <tr>
              <td className={'custom-table-title'}>标高</td>
              <td className={'custom-table-value'}>{pointData.elevation}</td>
            </tr>
            </tbody>
          </table>
          {
            window.location.pathname!=='/pipe_hsj_home'&& <span onClick={() => {
              this.setState({
                infoModal: true,
              });
            }} className={'success'} style={{cursor: 'pointer'}}>查看详情</span>
          }

          <span style={{cursor:'pointer',marginLeft:'10px'}} onClick={()=>{
            const exit=find(compare_data,function (item,index){
              return item.id===pointData.id
            })
            if(!exit){
              compare_data.unshift({id:pointData.id,name:pointData.name,number:pointData.number,address:pointData.address})
              console.log('compare_data0',compare_data)
              this.props.dispatch({
                type: 'global/changeOneProperty',
                payload: {
                  compare_data:compare_data
                },
              });
              message.success('加入对比成功')
            }else{
              message.error('该设备已经在对比列表')
            }
          }}>
            加入对比
          </span>
        </div>
      </div>
      <div className="table-condition" style={{position: 'absolute', left: '10px', top: '10px', color: '#fff'}}>
        {this.renderSimpleForm()}</div>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={800}
        visible={this.state.infoModal}
      >
        <Detail editRecord={this.state.editRecord}
                detailSaveCallback={()=>{
                  const {
                    pressure_sensors: { searchParams },
                  } = that.props;
                  that.handleSearch(searchParams);
                }}
        ></Detail>
      </Drawer>
      <Drawer
        title={`${this.state.editRecord2.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal2: false,
            editRecord2: {},
          });
        }}

        width={800}
        visible={this.state.infoModal2}
      >
        <Detail editRecord={this.state.editRecord2}
        ></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
